import { createStore, applyMiddleware } from "redux";
import thunkMiddleware from "redux-thunk";
import http from "../api/index.js";
import { connect } from "react-redux";

// 常量
const SYNC_USER_INFO = "SYNC_USER_INFO";

// 初始值
const defaultState = {
  userInfo: {},
};

// === getter ===
export function getUserInfo(state) {
  return state.userInfo;
}

// === actions ===
// 同步action
export function syncUserInfo(data) {
  return { type: SYNC_USER_INFO, data };
}

// 异步action
export function syncUserInfoAsync() {
  return async (dispatch) => {
    const res = await http.get("/getUserInfo");
    dispatch(syncUserInfo({ userInfo: res }));
    return res;
  };
}

// === reducer ===
function reducer(state = null, action) {
  const { type, data } = action;

  switch (type) {
    case SYNC_USER_INFO:
      return data;
    default:
      return defaultState;
  }
}

// === Store ===
// 创建store
const store = createStore(reducer, applyMiddleware(thunkMiddleware));

export default store;

// 映射状态
function mapStateToProps(state) {
  return {
    userInfo: getUserInfo(state),
  };
}

// 映射方法的简写形式
const mapDispatchToProps = {
  syncUserInfoAsync,
};

// 创建容器
export function createUserStore(component) {
  return connect(mapStateToProps, mapDispatchToProps)(component);
}
